#!/bin/bash
# TODO: 1. curl 2. cookie as variable

sites="xiami.com/album|xiami.com/song|xiami.com/artist|eyny.com|caramel623.k2-ani.com"
get_site() {
  echo "$1" | grep -Eo "$sites"
}

caramel623.k2-ani.com() {
  xml_url=`curl -s "$1" | grep container72 | grep -o 'http.*xml'`
  echo "${xml_url}"
  urls=(`curl -s -g "${xml_url}"|grep 'media:content'|cut -d'"' -f2`)
  # printf '%b' "${urls[@]//\%/\x}"
  [ -n "$2" ] && { wget --no-check-certificate "${urls[$2]}"; return 0; }
  wget --no-check-certificate "${urls[@]: -1}"
}

eyny.com() {
  logf=`curl -s -A iPad -b "video_size=720" "$1"`
  furl=`echo "$logf" | grep -o 'file:[^,]*' | cut -d"'" -f2`
  fname=`echo "$logf" | ack -m 1 -o 'title>\K.*(?=</title)'`
  fname=${fname% -*}
  if [[ $fname == *"&#"* ]]; then
    fname=$(python -c "import re; print re.sub('&#\w+;', lambda t: unichr(int(t.group(0)[2:-1])), '''${fname}'''.decode('utf8')).encode('utf8')")
  fi
  echo $fname $furl
  curl -# -C - -A iPad -b "PHPSESSID=3411b1e84538f8afb75770835c8806ac;video_size=720" "$furl" -o "$fname.mp4"
}

xiami.com/album() {
  aid=${1##*/}
  [ -f $aid.json ] || curl -f -s -A iPad "http://www.xiami.com/app/iphone/album/id/$aid" -o "$aid.json"
  cdc=`grep -o "cd_count[^,]*" $aid.json|head -n 1|cut -d'"' -f3`
  if [ $cdc -eq 1 ];then
    lst=`grep -o "location[^,]*" "$aid.json" |cut -d'"' -f 3|tr -d '\' |sort`
    echo "$lst"|while read url; do
      sid=`echo ${url##*/}`
      sid=${sid:0:2}
      curl -# -f -C - -A iPad "${url/ /%20}" -o $aid-$sid.mp3
    done
  else
    lst=`grep -Eo "(cd_serial|location)[^,]*" $aid.json|cut -d'"' -f 3|tr -d '\'|paste -s -d ' \n' -`
    echo "$lst"|while read cds url; do
      sid=`echo ${url##*/}`
      sid=${sid:0:2}
      curl -# -f -C - -A iPad "${url/ /%20}" -o $aid-$cds-$sid.mp3
    done
  fi
  xmtag.py "$aid.json"
}
xiami.com/song() {
  sid=${1##*/}
  json=`curl -f -s -A iPad "http://www.xiami.com/app/iphone/song/id/$sid"`
  aid=`echo $json|grep -o "album_id[^,]*"|cut -d'"' -f 3`
  name=`echo $json|grep -o "\<name[^,]*"|cut  -d'"' -f 3`
  name=`zsh -c "echo -e '$name'"`
  url=`echo $json|grep -o "location[^,]*" |cut -d'"' -f 3|tr -d '\'`
  echo $aid $name $url
  curl -# -f -A iPad "${url/ /%20}" -o "$aid-$name.mp3"
}
xiami.com/artist() {
  echo not done yet!
}

`get_site "$1"` "$@"
